package com.nontax.test.common.domain;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nontax.test.util.ObjectMapperUtil;
import com.nontax.test.util.StdRestSignUtil;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;

import java.io.Serializable;
import java.util.UUID;

@Getter
@Setter
@Slf4j
public class StdRespParameter implements Serializable {

    protected static ObjectMapper mapper = ObjectMapperUtil.getCustomInstance();
    /**
     *
     */
    private static final long serialVersionUID = 8044985396341932734L;

    private String data; // base64 json(对应单位端reqDTO)
    private String noise; // uuid or timestampe
    private String sign; // md5

    public static StdRespParameter generate(Object returnData,StdRestAppInfo stdRestAppInfo) throws Exception {
        //第一次 对象JSON化
        String json = JSON.toJSONString(returnData);
        log.info("返回data : {}", json);
        //第一次 BASE64处理
        String data = Base64.encodeBase64String(json.getBytes("UTF-8"));
        StdRespDetailParameter stdRespDetailParameter = new StdRespDetailParameter();
        stdRespDetailParameter.setResult(StdRestConst.SUCCESS_CODE);
        stdRespDetailParameter.setMessage(data);
        //第二次 对象JSON化
        json = mapper.writeValueAsString(stdRespDetailParameter);
        //第二次 BASE64处理
        data = Base64.encodeBase64String(json.getBytes("UTF-8"));
        // 构造返回参数对象
        StdRestParameter respParameter = new StdRestParameter();
        respParameter.setAppid("bs");
        respParameter.setNoise(UUID.randomUUID().toString().replace("-", ""));
        respParameter.setAppkey("999");
        respParameter.setVersion(StdRestConst.DEFAULT_VERSION);
        respParameter.setData(data);
        String sign = StdRestSignUtil.sign(respParameter);
        StdRespParameter resp = new StdRespParameter();
        resp.setData(respParameter.getData());
        resp.setNoise(respParameter.getNoise());
        resp.setSign(sign);
        return resp;
    }
}
